package com.li.admin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FormController {

    @RequestMapping("/form_layouts")
    public String form_layouts(){
        return "form/form_layouts";
    }

    /**
     * MultipartFile自动封装上传过来的文件
     * @param email
     * @param username
     * @param headerImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos
    ) throws IOException {
        if(!headerImg.isEmpty()){
            String originalFilename = headerImg.getOriginalFilename();
            UUID uuid = UUID.randomUUID();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            headerImg.transferTo(new File("D:\\WorkSpace\\cache\\" + uuid.toString() + suffix));
        }
        if(photos.length > 0){
            for(MultipartFile photo : photos){
                if(!photo.isEmpty()){
                    String originalFilename = photo.getOriginalFilename();
                    UUID uuid = UUID.randomUUID();
                    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                    photo.transferTo(new File("D:\\WorkSpace\\cache\\" + originalFilename));
                }
            }
        }
        System.out.println("email = " + email);
        System.out.println("username = " + username);
        System.out.println(headerImg.getSize());
        System.out.println(photos.length);
        return "main";
    }

}
